<?php

namespace App\Services;

use App\Notifications\VerificationCodeNotification;
use App\User;
use Cache;

use Overtrue\EasySms\EasySms;

class CodeService
{

    protected $account;


    public function send($account)
    {
        $this->account = $account;
        $code = mt_rand(1000, 9999);
        //类似js的apply和call
        call_user_func([$this, $this->action($account)], $code);
        Cache::put($this->key($account), $code, now()->addMinute(20));
    }

    protected function key($account)
    {
        return md5('verification-code-' . $account);
    }

    public function check($account, $value)
    {
        return Cache::get($this->key($account)) == $value;
    }

    public function action($account)
    {
        if (filter_var($account, FILTER_VALIDATE_EMAIL)) {
            return 'email';
        }
        if (preg_match('/^1\d{10}$/i', $account)) {
            return 'mobile';
        }
    }

    public function email($code)
    {

        return app(User::class)->fill(['email' => $this->account])->notify(new VerificationCodeNotification($code));
    }

    public function mobile($code)
    {
        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => '/tmp/easy-sms.log',
                ],

                'aliyun' => [
                    'access_key_id' => config('site.aliyun.accessKeyId'),
                    'access_key_secret' => config('site.aliyun.accessKeySecret'),
                    'sign_name' => config('site.sms.aliyun.sign'),
                ],

            ],
        ];

        $easySms = new EasySms($config);

        $callBack=$easySms->send($this->account, [
            'content' => '您的验证码为: 6379',
            'template' => config('site.sms.aliyun.template'),
            'data' => [
                'code' => $code,
            ],
        ]);

    }
}
